package com.yonyou.gmmc.service.shopping.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.marketing.common.FrameHttpUtil;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dms.dto.SendMessage;
import org.marketing.common.dto.carOwner.CarOwnerDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventShoppingSendWeixinDto;
import org.marketing.common.event.EventShoppingToPayDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.CookieSecurityUtil;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MapConverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.marketing.common.Response;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.shopping.constant.ShoppingConstant;
import com.yonyou.gmmc.service.shopping.dao.TmTpBalanceDetailMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpOrderInfoMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpOrderProductInfoMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpOrderStatusLogMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpProductCategoryMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpProductDetailBookMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpProductDetailGeneralMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpProductDetailMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpProductDetailVidoMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpReceiveAddMapper;
import com.yonyou.gmmc.service.shopping.dao.TmTpShoppingCarMapper;
import com.yonyou.gmmc.service.shopping.dao.TtEventHandleLogMapper;
import com.yonyou.gmmc.service.shopping.model.ReceiveAdd;
import com.yonyou.gmmc.service.shopping.model.TmTpBalanceDetail;
import com.yonyou.gmmc.service.shopping.model.TmTpOrderInfo;
import com.yonyou.gmmc.service.shopping.model.TmTpOrderProductInfo;
import com.yonyou.gmmc.service.shopping.model.TmTpOrderStatusLog;
import com.yonyou.gmmc.service.shopping.model.TmTpProductDetail;
import com.yonyou.gmmc.service.shopping.model.TmTpProductDetailBook;
import com.yonyou.gmmc.service.shopping.model.TmTpProductDetailGeneral;
import com.yonyou.gmmc.service.shopping.model.TmTpProductDetailVido;
import com.yonyou.gmmc.service.shopping.model.TmTpReceiveAdd;
import com.yonyou.gmmc.service.shopping.model.TmTpShoppingCar;
import com.yonyou.gmmc.service.shopping.model.TtEventHandleLog;
import com.yonyou.gmmc.service.shopping.service.ShoppingServiceInterface;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.mapper.entity.Example;

@Service
public class ShoppingOrderService extends BaseService {

    private static Logger                  logger       = LoggerFactory.getLogger(ShoppingOrderService.class);

    @Autowired
    private TtEventHandleLogMapper         ttEventHandleLogMapper;

    @Autowired
    private TmTpOrderInfoMapper            tmTpOrderInfoMapper;

    @Autowired
    private TmTpProductDetailMapper        tmTpProductDetailMapper;

    @Autowired
    private TmTpShoppingCarMapper          tmTpShoppingCarMapper;

    @Autowired
    private CustomerServiceInterface       customerServiceInterface;

    @Autowired
    private TmTpOrderProductInfoMapper     tmTpOrderProductInfoMapper;

    @Autowired
    private TmTpOrderStatusLogMapper       tmTpOrderStatusLogMapper;

    @Autowired
    private TmTpProductDetailGeneralMapper productDetailGeneralMapper;
    @Autowired
    private TmTpProductDetailVidoMapper    productDetailVidoMapper;
    @Autowired
    private TmTpProductDetailBookMapper    productDetailBookMapper;

    @Autowired
    private BaseService                    eventService;

    @Autowired
    private TmTpReceiveAddMapper           tmTpReceiveAddMapper;

    @Autowired
    private ShoppingServiceInterface       shoppingServiceInterface;

    @Value("${inforhost}")
    private String                         inforHost;

    @Autowired
    private TmTpBalanceDetailMapper        tmTpBalanceDetailMapper;

    @Autowired
    private TmTpProductCategoryMapper      tmTpProductCategoryMapper;
    /*
     * 下单固定参数
     */
    @Value("${INVOICESTATE}")
    private String                         INVOICESTATE;
    @Value("${INVOICETYPE}")
    private String                         INVOICETYPE;
    @Value("${SELECTEDINVOICETITLE}")
    private String                         SELECTEDINVOICETITLE;
    @Value("${INVOICECONTENT}")
    private String                         INVOICECONTENT;
    @Value("${PAYMENTTYPE}")
    private String                         PAYMENTTYPE;
    @Value("${SUBMITSTATE}")
    private String                         SUBMITSTATE;
    @Value("${ISUSEBALANCE}")
    private String                         ISUSEBALANCE;
    @Value("${DOORDERPRICEMODE}")
    private String                         DOORDERPRICEMODE;

    @Value("${RATIO}")
    private String                         RATIO;

    // 获取第三方积分url
    private static String                  getTotalURL  = "http://weixin1.gmmc.com.cn/api/integral/getTotal";

    // 扣分第三方url
    private static String                  deductionURL = "http://weixin1.gmmc.com.cn/api/integral/deduction";

    /**
     * 新增事件处理记录
     * 
     * @param event
     * @return
     */
    public int insertHandleLog(BizEvent event) {
        TtEventHandleLog log = new TtEventHandleLog();
        log.setBcId(event.getEventBizType().getCodeLong());
        log.setTcId(event.getEventBizStep().getCodeLong());
        log.setEventKey(event.getEventKey());
        if (event.getEventData().toString().length() > 3500) {
            log.setEventData(event.getEventData().toString().substring(0, 3500));
        } else {
            log.setEventData(event.getEventData().toString());
        }
        log.setCreateBy(ShoppingConstant.OPT_USER);
        log.setCreateDate(new Date());
        return ttEventHandleLogMapper.insertSelective(log);
    }

    /**
     * 查询数量
     * 
     * @param event
     * @return
     */
    public int queryEventNum(BizEvent event) {
        TtEventHandleLog log = new TtEventHandleLog();
        log.setBcId(event.getEventBizType().getCodeLong());
        log.setTcId(event.getEventBizStep().getCodeLong());
        log.setEventKey(event.getEventKey());
        log.setCreateBy(ShoppingConstant.OPT_USER);
        return ttEventHandleLogMapper.selectCount(log);
    }

    /**
     * 更新订单的对应的状态
     * 
     * @author QianKun
     * @date 2017年4月13日
     * @return
     */
    public String updateOrderStatus(TmTpOrderInfo orderInfo) throws Exception {
        String reuslt = "";
        try {
            // Example example = new Example(TmTpOrderInfo.class);
            // example.createCriteria().andCondition("THIRD_ORDER=", orderInfo.getThirdOrder());
            // 查询更新前的订单状态
            // List<TmTpOrderInfo> orderList = tmTpOrderInfoMapper.selectByExample(example);
            Map<String, Object> queryMap = new HashMap<String, Object>();
            queryMap.put("thirdOrder", orderInfo.getThirdOrder());
            List<TmTpOrderInfo> orderList = tmTpOrderInfoMapper.selectOrderStatus(queryMap);
            Long orderStatusBefore = Long.valueOf(orderList.get(0).getOrderStatus());
            // 更新订单状态
            int i = tmTpOrderInfoMapper.updateOrderStatus(orderInfo);
            logger.info("更新数——" + i);
            // 更新成功后添加一条订单状态更新日志
            logger.info("开始记录订单状态更新日志表");
            TmTpOrderStatusLog orderLog = new TmTpOrderStatusLog();
            orderLog.setThirdOrder(orderInfo.getThirdOrder());
            logger.info("单号——" + orderLog.getThirdOrder());
            orderLog.setOrderStatusBefore(orderStatusBefore);
            logger.info("订单更改前状态——" + orderLog.getOrderStatusBefore());
            orderLog.setOrderStatusAfter(Long.valueOf(orderInfo.getOrderStatus()));
            logger.info("订单更改后状态——" + orderLog.getOrderStatusAfter());
            orderLog.setCreateDate(new Date());
            logger.info("创建日期——" + orderLog.getCreateDate());
            orderLog.setCreateBy(Long.valueOf(ShoppingConstant.OPT_USER));
            logger.info("创建人——" + orderLog.getCreateBy());
            int s = tmTpOrderStatusLogMapper.insertSelective(orderLog);
            logger.info("日志表更新数——" + s);
            reuslt = "已成功更新订单状态";
        } catch (Exception e) {
            logger.error("", e);
            e.printStackTrace();
            reuslt = "更新订单状态失败";
        }
        return reuslt;
    }

    /**
     * 保存订单
     * 
     * @author QianKun
     * @date 2017年4月14日
     * @return
     */
    public Map<String, Object> saveOrderInfo(TmTpOrderInfo tmTpOrderInfo, String openId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        Long sumNum = 0L;
        Double sumPrice = 0.0;
        Boolean areas = true;
        Boolean stocks = true;
        Boolean add = true;
        Boolean statusUp = true;
        try {
            // 根据OPENID拿到车主ID
//            List<CarOwnerDto> userDto = customerServiceInterface.getUserInfo(openId);
            String userid = tmTpOrderInfoMapper.queryUserIdByOpenId(openId);
            if (CheckUtil.NullOrEmpty(userid)) {
                // 非车主
                logger.info("不是车主！");
                result.put("flag", 0);
                result.put("msg", "您当前还不是会员，不能兑换商品！");
            } else {
                // 将车主ID存入实体
                tmTpOrderInfo.setUserId(Long.valueOf(userid));
                BigDecimal userId = BigDecimal.valueOf(tmTpOrderInfo.getUserId());
                logger.info("车主ID——" + userId);
                try {
                    TmTpShoppingCar tmTpShoppingCar = new TmTpShoppingCar();
                    // 先判断积分是否充足
                    Map<String, Object> checkResult = checkShoppingCar(tmTpShoppingCar, userId, openId);
                    logger.info("积分校验结果" + checkResult);
                    boolean flags = Boolean.valueOf(checkResult.get("flag").toString());
                    logger.info("校验结果--------------" + flags);
                    Double points = Double.valueOf(checkResult.get("points").toString());
                    logger.info("积分》》》》》》" + points);
                    if (!flags) {
                        // 积分不足
                        result.put("flag", 0);
                        result.put("msg", "您当前积分余额不足，不能下单！");
                        return result;
                    } else {
                        // 积分足够
                        // 查询该车主的收货地址
                        Example ex = new Example(TmTpReceiveAdd.class);
                        ex.createCriteria().andCondition("USER_ID=", tmTpOrderInfo.getUserId());
                        List<TmTpReceiveAdd> receiveAddList = tmTpReceiveAddMapper.selectByExample(ex);
                        // 校验收货信息是否正确
                        if (receiveAddList.size() == 0) {
                            // 没有查到收货地址
                            result.put("flag", 0);
                            result.put("msg", "请维护您的收货地址");
                            return result;
                        } else {
                            try {
                                for (int i = 0; i < receiveAddList.size(); i++) {
                                    if (receiveAddList.get(i).getFirstAddCode() == null
                                        || receiveAddList.get(i).getSecondAddCode() == null
                                        || receiveAddList.get(i).getThirdAddCode() == null) {
                                        logger.info("1-3级地址中存在空");
                                        result.put("flag", 0);
                                        result.put("msg", "地址不正确，请重新维护!");
                                        return result;
                                    } else {
                                        if (receiveAddList.get(i).getCommentAdd() == null
                                            || receiveAddList.get(i).getReceiveName() == null
                                            || receiveAddList.get(i).getReceivePhone() == null) {
                                            logger.info("收件人信息存在空");
                                            result.put("flag", 0);
                                            result.put("msg", "地址不正确，请重新维护!");
                                            return result;
                                        } else {
                                            tmTpOrderInfo.setProvince(receiveAddList.get(i).getFirstAddCode());
                                            tmTpOrderInfo.setCity(receiveAddList.get(i).getSecondAddCode());
                                            tmTpOrderInfo.setCounty(receiveAddList.get(i).getThirdAddCode());
                                            tmTpOrderInfo.setTown(receiveAddList.get(i).getFourthAddCode());
                                            logger.info("四级地址为：" + tmTpOrderInfo.getProvince() + "-"
                                                        + tmTpOrderInfo.getCity() + "-" + tmTpOrderInfo.getCounty()
                                                        + "-" + tmTpOrderInfo.getTown());
                                            tmTpOrderInfo.setAddress(receiveAddList.get(i).getCommentAdd());
                                            logger.info("详细收货地址--------------" + tmTpOrderInfo.getAddress());
                                            tmTpOrderInfo.setName(receiveAddList.get(i).getReceiveName());
                                            logger.info("收件人姓名--------------" + tmTpOrderInfo.getName());
                                            tmTpOrderInfo.setMobile(receiveAddList.get(i).getReceivePhone());
                                            logger.info("收件人手机--------------" + tmTpOrderInfo.getMobile());
                                            tmTpOrderInfo.setEmail(receiveAddList.get(i).getEmail());
                                            logger.info("收件人邮箱--------------" + tmTpOrderInfo.getEmail());

                                            // 查询购物车中的商品信息
                                            TmTpOrderProductInfo productInfo = new TmTpOrderProductInfo();
                                            List<TmTpShoppingCar> shoppingCarList = new ArrayList<TmTpShoppingCar>();
                                            try {
                                                shoppingCarList = tmTpShoppingCarMapper.selectJDprice(userId);
                                                if (shoppingCarList.size() == 0) {
                                                    logger.info("没有商品");
                                                    result.put("flag", 0);
                                                    result.put("msg", "当前购物车中没有任何商品");
                                                    return result;
                                                } else {
                                                    // 有商品，校验是否上架了
                                                    try {
                                                        for (TmTpShoppingCar sDto : shoppingCarList) {
                                                            String wxstate = sDto.getWxState();
                                                            String pdState = sDto.getState();
                                                            if (wxstate.equals(ShoppingConstant.WX_STATUS_UP.toString())
                                                                && pdState.equals(ShoppingConstant.STATUS_UP.toString())) {
                                                                // 上架状态
                                                                logger.info("商品状态正常，上架" + sDto.getSkuId());
                                                            } else {
                                                                // 下架了
                                                                logger.info("该商品已下架" + sDto.getSkuId());
                                                                statusUp = false;
                                                                result.put("flag", 0);
                                                                result.put("msg", "您的购物车中含有下架商品，请先清理后再下单");
                                                                return result;
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        logger.info("Exception:", e);
                                                        result.put("flag", 0);
                                                        result.put("msg", "下单异常！");
                                                        return result;
                                                    }
                                                    // 计算订单总价
                                                    for (TmTpShoppingCar scDto : shoppingCarList) {
                                                        // 计算总数
                                                        sumNum = sumNum + scDto.getNum();
                                                        // 计算总价
                                                        Double price = Double.valueOf(scDto.getPrice());
                                                        Double num = scDto.getNum().doubleValue();
                                                        sumPrice = sumPrice + (price * num);
                                                    }
                                                }
                                            } catch (Exception e) {
                                                logger.info("Exception:", e);
                                                result.put("flag", 0);
                                                result.put("msg", "下单异常！");
                                                return result;
                                            }

                                            /**
                                             * 2017.11.22 暂时不用调用JD接口 try { // 调用地域限制查询接口 // 拼接参数 Map<String, Object>
                                             * areaLimitParams = new HashMap<String, Object>(); String skus = ""; String
                                             * nums = ""; if (shoppingCarList.size() == 1) { skus =
                                             * shoppingCarList.get(0).getSkuId(); } else { for (int t = 0; t <
                                             * shoppingCarList.size(); t++) { if (i == shoppingCarList.size() - 1) {
                                             * skus = skus + shoppingCarList.get(t).getSkuId(); nums = nums +
                                             * shoppingCarList.get(t).getNum(); } else { skus = skus +
                                             * shoppingCarList.get(t).getSkuId() + ","; nums = nums +
                                             * shoppingCarList.get(t).getNum() + ","; } } }
                                             * areaLimitParams.put("skuIds", skus); areaLimitParams.put("province",
                                             * tmTpOrderInfo.getProvince()); areaLimitParams.put("city",
                                             * tmTpOrderInfo.getCity()); areaLimitParams.put("county",
                                             * tmTpOrderInfo.getCounty()); areaLimitParams.put("town",
                                             * tmTpOrderInfo.getTown()); // 调用接口 Response areaLimitResult =
                                             * shoppingServiceInterface.checkAreaLimit(areaLimitParams);
                                             * logger.info("返回结果——" + areaLimitResult); List<Map<String, Object>>
                                             * areaLimitList = (List<Map<String, Object>>) areaLimitResult.getData();
                                             * logger.info("返回Data——" + areaLimitList); for (int a = 0; a <
                                             * areaLimitList.size(); a++) { Map<String, Object> areaLimitData =
                                             * areaLimitList.get(a); Integer skuId = (Integer)
                                             * areaLimitData.get("skuId"); Boolean isAreaRestrict = (Boolean)
                                             * areaLimitData.get("isAreaRestrict"); if (isAreaRestrict) { // 该订单商品存在地域限制
                                             * logger.info("该商品存在地域限制——" + skuId); areas = false; //
                                             * 修改存在问题的商品在该用户购物车中的状态——状态为无权限购买 // 创建Example Example areaExample = new
                                             * Example(TmTpShoppingCar.class);
                                             * areaExample.createCriteria().andCondition("SKU_ID=",
                                             * skuId).andCondition("USER_ID=", tmTpOrderInfo.getUserId());
                                             * TmTpShoppingCar areaDto = new TmTpShoppingCar();
                                             * areaDto.setStatus(ShoppingConstant.SHOPPING_CAR_AREALIMIT);
                                             * areaDto.setUpdateDate(new Date()); int b =
                                             * tmTpShoppingCarMapper.updateByExampleSelective(areaDto, areaExample);
                                             * logger.info("更新数:" + b); } else { // 该订单商品不存在地域限制
                                             * logger.info("该商品不存在地域限制——" + skuId); // Example areaExample = new
                                             * Example(TmTpShoppingCar.class); // areaExample.createCriteria() //
                                             * .andCondition("SKU_ID=", skuId) //
                                             * .andCondition("USER_ID=",tmTpOrderInfo.getUserId()); // //
                                             * TmTpShoppingCar areaDto = new TmTpShoppingCar(); //
                                             * areaDto.setStatus(ShoppingConstant.SHOPPING_CAR_INFINITIZE); // int a =
                                             * // tmTpShoppingCarMapper.updateByExampleSelective(areaDto, //
                                             * areaExample); // logger.info("更新数:"+a); } } } catch (Exception e) {
                                             * logger.info("Exception:", e); result.put("flag", 0); result.put("msg",
                                             * "订单中存在不可购买的商品"); return result; }
                                             */

                                            /**
                                             * 2017.11.22 暂时不用调用JD接口 try { // 调用库存查询接口 // 拼接参数 Map<String, Object>
                                             * newStockParams = new HashMap<String, Object>(); List<Map<String, Object>>
                                             * skuNums = new ArrayList<Map<String, Object>>(); if
                                             * (shoppingCarList.size() == 1) { Map<String, Object> skuMap = new
                                             * HashMap<String, Object>(); skuMap.put("skuId",
                                             * shoppingCarList.get(0).getSkuId()); skuMap.put("num",
                                             * shoppingCarList.get(0).getNum()); skuNums.add(skuMap); } else { for (int
                                             * c = 0; c < shoppingCarList.size(); c++) { Map<String, Object> skuMap =
                                             * new HashMap<String, Object>(); skuMap.put("skuId",
                                             * shoppingCarList.get(c).getSkuId()); skuMap.put("num",
                                             * shoppingCarList.get(c).getNum()); skuNums.add(skuMap); } } String area =
                                             * tmTpOrderInfo.getProvince() + "_" + tmTpOrderInfo.getCity() + "_" +
                                             * tmTpOrderInfo.getCounty() + "_" + tmTpOrderInfo.getTown();
                                             * newStockParams.put("skuNums", skuNums); newStockParams.put("area", area);
                                             * // 调用接口 Response newStockResult =
                                             * shoppingServiceInterface.getNewStockById(newStockParams);
                                             * logger.info("返回结果——" + newStockResult); List<Map<String, Object>>
                                             * newStockList = (List<Map<String, Object>>) newStockResult.getData();
                                             * logger.info("返回Data——" + newStockList); if (newStockList == null) {
                                             * logger.info("接口调用失败——" + newStockResult.getErrMsg()); } else { for (int d
                                             * = 0; d < newStockList.size(); d++) { Map<String, Object> newStockData =
                                             * newStockList.get(d); Integer skuId = (Integer) newStockData.get("skuId");
                                             * Integer stockStateId = (Integer) newStockData.get("stockStateId"); String
                                             * stockStateDesc = (String) newStockData.get("stockStateDesc"); if
                                             * (stockStateId == 34) { // 订单中某些商品库存不足 logger.info("该商品库存不足——" + skuId);
                                             * stocks = false; // 修改存在问题的商品在该用户购物车中的状态——状态为库存不足 // 创建Example Example
                                             * stockExample = new Example(TmTpShoppingCar.class);
                                             * stockExample.createCriteria().andCondition("SKU_ID=",
                                             * skuId).andCondition("USER_ID=", tmTpOrderInfo.getUserId());
                                             * TmTpShoppingCar stockDto = new TmTpShoppingCar();
                                             * stockDto.setStatus(ShoppingConstant.SHOPPING_CAR_STOCK_INSUFFICIENT);
                                             * stockDto.setUpdateDate(new Date()); int a =
                                             * tmTpShoppingCarMapper.updateByExampleSelective(stockDto, stockExample);
                                             * logger.info("更新数:" + a); } else { // 订单中商品不存在库存问题 logger.info("该商品库存充足——"
                                             * + skuId); // Example stockExample = new //
                                             * Example(TmTpShoppingCar.class); // stockExample.createCriteria() //
                                             * .andCondition("SKU_ID=", skuId) //
                                             * .andCondition("USER_ID=",tmTpOrderInfo.getUserId()); // //
                                             * TmTpShoppingCar stockDto = new TmTpShoppingCar(); //
                                             * stockDto.setStatus(ShoppingConstant.SHOPPING_CAR_STOCK_ENOUGH); // int a
                                             * = // tmTpShoppingCarMapper.updateByExampleSelective(stockDto, //
                                             * stockExample); // logger.info("更新数:"+a); } } } } catch (Exception e) {
                                             * logger.info("Exception:", e); result.put("flag", 0); result.put("msg",
                                             * "订单中存在库存不足的商品"); return result; }
                                             */
                                            /**
                                             * 2017.11.22 暂时不用调用JD接口 try { // 调用校验JD地址接口 Map<String, Long>
                                             * checkAddParams = new HashMap<String, Long>(); // 拼接参数
                                             * checkAddParams.put("provinceId", tmTpOrderInfo.getProvince());
                                             * checkAddParams.put("cityId", tmTpOrderInfo.getCity());
                                             * checkAddParams.put("countyId", tmTpOrderInfo.getCounty());
                                             * checkAddParams.put("townId", tmTpOrderInfo.getTown()); // 调用接口 Response
                                             * checkAddResult = shoppingServiceInterface.checkFourAdd(checkAddParams);
                                             * logger.info("返回结果——" + checkAddResult); List<Map<String, Object>>
                                             * checkAddList = (List<Map<String, Object>>) checkAddResult.getData();
                                             * logger.info("返回Data——" + checkAddList); for (int e = 0; e <
                                             * checkAddList.size(); e++) { Map<String, Object> checkAddData =
                                             * checkAddList.get(e); String success = (String)
                                             * checkAddData.get("success"); if (success.equals("true")) { // 该订单地址校验通过
                                             * logger.info("该订单地址校验无误！"); } else { // 该订单地址校验不通过
                                             * logger.info("该订单地址校验有误！"); add = false; String errMsg = (String)
                                             * checkAddData.get("message"); result.put("flag", 0); result.put("msg",
                                             * errMsg); return result; } } } catch (Exception e) {
                                             * logger.info("Exception:", e); result.put("flag", 0); result.put("msg",
                                             * "地址校验不通过，请重新维护"); return result; }
                                             */
                                            if (areas && stocks && add && statusUp) {
                                                // 该订单中的商品不存在地域限制，也不存在库存不足问题,地址校验也能通过,商品也都上架了
                                                // 生成本次订单单号
                                                String orderNum = tmTpOrderInfoMapper.selectOrderNum(tmTpOrderInfo);
                                                tmTpOrderInfo.setThirdOrder(orderNum);
                                                logger.info("本次第三方单号为：" + tmTpOrderInfo.getThirdOrder());
                                                tmTpOrderInfo.setOrderStatus(ShoppingConstant.ORDER_STATUS_START);
                                                logger.info("订单状态——" + tmTpOrderInfo.getOrderStatus());
                                                Integer sumPrices = (int) Math.ceil(sumPrice);
                                                tmTpOrderInfo.setOrderPrice(sumPrices.toString());
                                                logger.info("本次订单总价——" + tmTpOrderInfo.getOrderPrice());

                                                // 添加固定参数
                                                tmTpOrderInfo.setInvoiceState(Long.valueOf(INVOICESTATE));
                                                tmTpOrderInfo.setInvoiceType(Long.valueOf(INVOICETYPE));
                                                tmTpOrderInfo.setSelectedInvoiceTitle(Long.valueOf(SELECTEDINVOICETITLE));
                                                tmTpOrderInfo.setInvoiceContent(Long.valueOf(INVOICECONTENT));
                                                tmTpOrderInfo.setPaymentType(Long.valueOf(PAYMENTTYPE));
                                                tmTpOrderInfo.setSubmitState(Long.valueOf(SUBMITSTATE));
                                                tmTpOrderInfo.setIsUseBalance(Long.valueOf(ISUSEBALANCE));
                                                tmTpOrderInfo.setDoOrderPriceMode(Long.valueOf(DOORDERPRICEMODE));

                                                // 保存订单
                                                tmTpOrderInfo.setOrderStatus(ShoppingConstant.ORDER_STATUS_SUCCESS);
                                                tmTpOrderInfoMapper.insertOrder(tmTpOrderInfo);
                                                // result.put("errorCode", "0");
                                                // result.put("resultMsg", "保存成功");
                                                logger.info("保存结果" + result);

                                                // 将购物车中的商品添加到订单商品详情表
                                                List<TmTpOrderProductInfo> OrderProduct = new ArrayList<TmTpOrderProductInfo>();
                                                for (TmTpShoppingCar scDto : shoppingCarList) {
                                                    productInfo.setSkuId(scDto.getSkuId());
                                                    logger.info("商品编码" + productInfo.getSkuId());
                                                    productInfo.setNum(scDto.getNum());
                                                    logger.info("数量" + productInfo.getNum());
                                                    productInfo.setThirdOrder(tmTpOrderInfo.getThirdOrder());
                                                    logger.info("第三方订单号——" + productInfo.getThirdOrder());
                                                    productInfo.setPrice(scDto.getPrice());
                                                    logger.info("价格price——" + productInfo.getPrice());
                                                    productInfo.setJdPrice(scDto.getJdPrice());
                                                    productInfo.setBneedAnnex("true");
                                                    productInfo.setBneedGift("true");
                                                    productInfo.setYanbao("");
                                                    productInfo.setPointsPrice(RATIO);
                                                    // OrderProduct.add(productInfo);
                                                    int f = tmTpOrderProductInfoMapper.insertOrderInfo(productInfo);
                                                    logger.info("插入了" + f + "条");
                                                }

                                                // 获取扣分事件所需参数
                                                BizEvent event = new BizEvent();
                                                Map<String, Object> queryMap = new HashMap<String, Object>();
                                                // 获取潜客类型
                                                String sourceTypeStr = tmTpProductDetailMapper.querySourceType(openId);
                                                Integer sourceTypeInt = Integer.valueOf(sourceTypeStr);
                                                logger.info("获取潜客类型：" + sourceTypeInt);
                                                if (sourceTypeInt == 10011002) {
                                                    Long deductPoints = points.longValue();
                                                    // String x = shoppingSendMq(openId,deductPoints);
                                                    // logger.info("MQ返回信息>>>>"+x);
                                                    // 添加参数
                                                    logger.info("用户类型为销售顾问");
                                                    queryMap.put("userType", "2");
                                                    queryMap.put("openId", openId);
                                                    queryMap.put("deductPoints", deductPoints);
                                                } else {
                                                    // 发送京东下单成功事件
                                                    logger.info("JD订单提交结果事件————Start");
                                                    EventShoppingToPayDTO orderEventDto = new EventShoppingToPayDTO();
                                                    orderEventDto.setPhone(tmTpOrderInfo.getMobile());
                                                    logger.info("下单的手机号——" + orderEventDto.getPhone());
                                                    Integer price = points.intValue();
                                                    orderEventDto.setPointsNum(price.longValue());
                                                    logger.info("订单需要扣减的金额——" + orderEventDto.getPointsNum());
                                                    orderEventDto.setShoppingOrderNo(tmTpOrderInfo.getThirdOrder());
                                                    logger.info("订单号——" + orderEventDto.getShoppingOrderNo());
                                                    orderEventDto.setUserId(Integer.valueOf(tmTpOrderInfo.getUserId().toString()));
                                                    logger.info("下单的用户id——" + orderEventDto.getUserId());
                                                    event.setEventBizType(EventBizType.SHOPPIING_ORDER);
                                                    event.setEventBizStep(EventBizStep.SHOPPIING_ORDER_JD);
                                                    event.setEventKey(orderEventDto.getShoppingOrderNo());
                                                    event.setEventData(MapConverUtil.PO2Map(orderEventDto));
                                                    // 添加参数
                                                    logger.info("用户类型为微信用户");
                                                    queryMap.put("userType", "1");
                                                    queryMap.put("phone", tmTpOrderInfo.getMobile());
                                                    queryMap.put("PointsNum", price.longValue());
                                                    // eventService.sendEvent2MQ(event);
                                                    String x = eventService.sendEvent2MQ(event);
                                                    logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
                                                    logger.info("用户下单事件————End");
                                                    result.put("flag", 1);
                                                    result.put("msg", "下单完成,待确认");
                                                    // return result;
                                                }

                                                /**
                                                 * 2017.11.22 暂时不用调用JD接口 // 调用京东下单接口 Map<String, String> resultMap = new
                                                 * HashMap<String, String>(); // 添加参数 queryMap.put("thirdOrder",
                                                 * tmTpOrderInfo.getThirdOrder()); queryMap.put("userId",
                                                 * tmTpOrderInfo.getUserId().toString()); resultMap =
                                                 * submitJDOrder(queryMap); String resultCode =
                                                 * resultMap.get("resultCode").toString();
                                                 * logger.info("调用京东接口返回码>>>>>>>>>>>>>>>>" + resultCode); String
                                                 * resultMsg = resultMap.get("resultMsg").toString();
                                                 * logger.info("调用京东接口返回信息>>>>>>>>>>>>>>>" + resultMsg); if
                                                 * (resultCode.equals(ShoppingConstant.ORDER_STATUS_SUCCESS)) { // 成功
                                                 * try { // 更新订单状态 TmTpOrderInfo orderInfo = new TmTpOrderInfo();
                                                 * orderInfo.setThirdOrder(tmTpOrderInfo.getThirdOrder());
                                                 * logger.info("要更新的单号>>>>>>>>>>>>" + orderInfo.getThirdOrder());
                                                 * orderInfo.setOrderStatus(ShoppingConstant.ORDER_STATUS_SUCCESS);
                                                 * logger.info("更新的状态为>>>>>>>>>>>>" + orderInfo.getOrderStatus());
                                                 * String s = updateOrderStatus(orderInfo);
                                                 * logger.info("更新结果>>>>>>>>>>>>>>>" + s); result.put("flag", 1);
                                                 * result.put("msg", "下单完成,待确认"); } catch (Exception e) {
                                                 * logger.info("Exception:", e); logger.info("扣分失败"); } } else { // 失败
                                                 * try { // 更新订单状态 TmTpOrderInfo orderInfo = new TmTpOrderInfo();
                                                 * orderInfo.setThirdOrder(tmTpOrderInfo.getThirdOrder());
                                                 * logger.info("要更新的单号>>>>>>>>>>>>" + orderInfo.getThirdOrder());
                                                 * orderInfo.setOrderStatus(ShoppingConstant.ORDER_STATUS_FIALED);
                                                 * logger.info("更新的状态为>>>>>>>>>>>>" + orderInfo.getOrderStatus());
                                                 * String s = updateOrderStatus(orderInfo);
                                                 * logger.info("更新结果>>>>>>>>>>>>>>>" + s); result.put("flag", 0);
                                                 * result.put("msg", "下单失败,请重新下单"); return result; } catch (Exception e)
                                                 * { logger.info("Exception:", e); logger.info("更新状态失败"); } }
                                                 */
                                            } else {
                                                result.put("flag", 0);
                                                result.put("msg", "该订单中存在问题，请重新下单");
                                                return result;
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                logger.info("Exception:", e);
                                result.put("flag", 0);
                                result.put("msg", "地址不正确，请重新维护");
                                return result;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.info("Exception:", e);
                    result.put("flag", 0);
                    result.put("msg", "下单异常！");
                    return result;
                }
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            result.put("flag", 0);
            result.put("msg", "下单异常！");
            return result;
        }
        return result;
    }

    /**
     * 订单查询
     * 
     * @author Administrator TODO description
     * @date 2017年4月20日
     * @param thirdOrder
     * @param openId
     * @return
     * @throws Exception
     */
    public Map<String, Object> getOrderInfoList(String thirdOrder, String openId, String orderStatus) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createDateStr = null;
        // 根据OPENID拿到车主ID
//        List<CarOwnerDto> userDto = customerServiceInterface.getUserInfo(openId);
        String userid = tmTpOrderInfoMapper.queryUserIdByOpenId(openId);
        Long sumNum = 0L;
        Long sumPrice = 0L;
        Double JDNum = 0.0;
        Double JDPrice = 0.0;
        Long totalPrice = 0L;
        Long feightPrice = 0L;
        if (CheckUtil.NullOrEmpty(userid)) {
            // 非车主
            logger.info("您当前还不是会员，不能兑换商品！");
        } else {
            // 将车主ID存入实体
            BigDecimal userId = new BigDecimal(userid);
            // 判断是查询列表还是详情
            if (thirdOrder == null || thirdOrder.length() == 0) {
                // 列表查询
                logger.info("订单列表查询");
                Map<String, Object> queryMap = new HashMap<String, Object>();
                queryMap.put("orderStatus", orderStatus);
                queryMap.put("userId", userId);
                List<TmTpOrderInfo> orderList = tmTpOrderInfoMapper.selectOrderList(queryMap);
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                for (TmTpOrderInfo po : orderList) {
                    Map<String, Object> orderMap = new HashMap<String, Object>();
                    orderMap.put("thirdOrder", po.getThirdOrder());
                    orderMap.put("codeName", po.getCodeName());
                    orderMap.put("createDate", DateUtil.formateDate(po.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                    // if (po.getOrderPrice() != null && Integer.valueOf(po.getOrderPrice()).intValue() < 99) {
                    // po.setOrderPrice(String.valueOf(Integer.valueOf(po.getOrderPrice()).intValue() + 6));
                    // }
                    orderMap.put("jdOrderId", po.getJdOrderId());
                    // 计算运费
                    Double sum = Double.valueOf(po.getJdPrice());
                    logger.info("该订单JD总价sum为>>>>>" + sum);
                    Long price = 0L;
                    logger.info("计算商品总价格加上运费");
                    if (sum >= 99) {
                        price = Long.valueOf(po.getOrderPrice());
                    } else {
                        price = Long.valueOf(po.getOrderPrice()) + 6;
                        feightPrice = 6L;
                    }
                    orderMap.put("orderPrice", price);

                    //
                    List<Map<String, Object>> proList = tmTpOrderInfoMapper.selectPeoductList(po.getThirdOrder());
                    orderMap.put("proList", proList);
                    //
                    list.add(orderMap);
                }
                resultMap.put("List", list);
            } else {
                // 详情查询
                logger.info("订单详情查询");
                Map<String, Object> queryMap = new HashMap<String, Object>();
                queryMap.put("thirdOrder", thirdOrder);
                queryMap.put("userId", userId);
                queryMap.put("orderStatus", orderStatus);
                List<Map<String, Object>> orderInfo = tmTpOrderInfoMapper.selectOrderInfo(queryMap);
                // 查询订单详情状态
                List<TmTpOrderInfo> statusMap = tmTpOrderInfoMapper.selectOrderStatus(queryMap);
                // 时间格式转换
                if (statusMap.size() == 0) {
                    createDateStr = sdf.format(new Date());
                } else {
                    if (statusMap.get(0).getCreateDate() == null) {
                        createDateStr = sdf.format(new Date());
                    } else {
                        createDateStr = DateUtil.formateDate(statusMap.get(0).getCreateDate(), "yyyy-MM-dd HH:mm:ss");
                    }
                }
                // 计算订单总价
                for (Map<String, Object> scDto : orderInfo) {
                    // 计算总数
                    sumNum = sumNum + Integer.valueOf(scDto.get("NUM").toString());
                    // 计算总价
                    sumPrice = sumPrice + ((Integer.valueOf(scDto.get("PRICE").toString())
                                            * Integer.valueOf(scDto.get("NUM").toString())));
                }
                logger.info("计算订单总价");
                // 京东总价
                for (Map<String, Object> scDto : orderInfo) {
                    // 计算总数
                    JDNum = JDNum + Integer.valueOf(scDto.get("NUM").toString());
                    // 计算总价
                    JDPrice = JDPrice + ((Double.valueOf(scDto.get("JDPRICE").toString())
                                          * Double.valueOf(scDto.get("NUM").toString())));
                }
                logger.info("该订单JDPRICE总价为>>>>>" + JDPrice);
                // 计算商品总价格加上运费
                if (JDPrice >= 99) {
                    totalPrice = sumPrice;
                } else {
                    sumPrice = sumPrice + 6;
                    totalPrice = sumPrice;
                    feightPrice = 6L;
                }

                resultMap.put("List", orderInfo);
                resultMap.put("StatusMap", statusMap);
                resultMap.put("sumNum", sumNum);
                resultMap.put("sumPrice", sumPrice);
                resultMap.put("totalPrice", totalPrice);
                resultMap.put("feightPrice", feightPrice);
                resultMap.put("createDateStr", createDateStr);

            }
        }
        return resultMap;
    }

    /**
     * PC订单查询
     * 
     * @author Administrator TODO description
     * @date 2017年4月20日
     * @param thirdOrder
     * @param openId
     * @return
     */
    public PageInfo<TmTpOrderInfo> getOrderList(Map<String, Object> paramMap){

    	// 查询商品列表
        Page<TmTpOrderInfo> ss = PageHelper.startPage(Integer.parseInt(paramMap.get("pageNum").toString()),
                                                      Integer.parseInt(paramMap.get("pageSize").toString()));
        logger.info("ss为————" + ss);

        List<TmTpOrderInfo> orderList = tmTpOrderInfoMapper.queryOrderList(paramMap);
        PageInfo<TmTpOrderInfo> page = new PageInfo<TmTpOrderInfo>(orderList);
        logger.info("page为————" + page);
        return page;
    }

    /**
     * 导出订单信息
     * 
     * @author Administrator TODO description
     * @date 2017年4月20日
     * @param thirdOrder
     * @param openId
     * @return
     */
    public List<TmTpOrderInfo> getOrderListExport(Map<String, Object> paramMap) {

    	List<TmTpOrderInfo> orderList = tmTpOrderInfoMapper.queryOrderList(paramMap);
        return orderList;
    }

    /**
     * PC订单详情查询
     * 
     * @author Administrator TODO description
     * @date 2017年4月20日
     * @param thirdOrder
     * @param openId
     * @return
     * @throws Exception
     */
    public Map<String, Object> getOrderInfo(Map<String, Object> paramMap) {

    	Map<String, Object> result = new HashMap<>();
        List<TmTpOrderInfo> orderList = tmTpOrderInfoMapper.queryOrderList(paramMap);
        result.put("orderList", orderList);
        String orderId = paramMap.get("thirdOrder").toString();
        List<Map<String, Object>> productList = tmTpOrderInfoMapper.selectPeoductList(orderId);
        result.put("productList", productList);
        return result;
    }

    /**
     * 保存购物车信息
     * 
     * @author QianKun
     * @date 2017年4月17日
     * @param tmTpShoppingCar
     * @return
     */
    public Map<String, Object> saveShoppingCar(TmTpShoppingCar tmTpShoppingCar, String openId) {
        Map<String, Object> result = new HashMap<>();
        // 创建日期对象
        Date d = new Date();

        // 根据OPENID拿到车主ID
//        List<CarOwnerDto> userDto = customerServiceInterface.getUserInfo(openId);
        String userid = tmTpOrderInfoMapper.queryUserIdByOpenId(openId);
        if (CheckUtil.NullOrEmpty(userid)) {
            // 非车主
            result.put("flag", 0);
            result.put("msg", "您当前还不是会员，不能兑换商品！");
            return result;
        }

        /*
         * if(!checkShoppingCar(tmTpShoppingCar,userId,openId)){ // 积分不足 result.put("flag", 0); result.put("msg",
         * "您当前积分余额不足，不能添加商品！"); }
         */else {
            // 将车主ID存入实体
            BigDecimal userId = new BigDecimal(userid);
            tmTpShoppingCar.setUserId(userId);
            logger.info("车主ID——" + tmTpShoppingCar.getUserId());
            try {
                // 查询该车主在购物车中是否已存在此商品的记录
                TmTpShoppingCar shoppingCarDto = new TmTpShoppingCar();
                shoppingCarDto = tmTpShoppingCarMapper.selectIfExist(tmTpShoppingCar);
                if (shoppingCarDto == null) {
                    // 不存在,新增一条
                    // 拿到商品数量
                    if (tmTpShoppingCar.getNum() == null) {
                        // 没有传入商品数量，默认为1
                        tmTpShoppingCar.setNum((long) 1);
                    }
                    tmTpShoppingCar.setCreateDate(d);
                    // 设置购物车商品初始状态
                    tmTpShoppingCar.setStatus(ShoppingConstant.SHOPPING_CAR_START);
                    tmTpShoppingCarMapper.insertShoppingCar(tmTpShoppingCar);
                    result.put("flag", 1);
                    result.put("msg", "商品添加成功！");
                } else {
                    // 存在,更新该记录
                    // 拿到商品数量
                    if (tmTpShoppingCar.getNum() == null) {
                        // 没有传入商品数量，默认为1
                        tmTpShoppingCar.setNum((long) (shoppingCarDto.getNum() + 1));
                    }
                    tmTpShoppingCarMapper.updateShoppingCar(tmTpShoppingCar);
                    result.put("flag", 1);
                    result.put("msg", "商品添加成功！");
                }
            } catch (Exception e) {
                logger.info("Exception:", e.getMessage());
                result.put("flag", 0);
                result.put("msg", "添加购物车失败！");
                throw new ServiceBizException(e.getMessage(), e);
            }
        }
        return result;
    }

    /**
     * 购物车积分余额校验
     * 
     * @author lyq
     * @date 2017年4月17日
     * @param tmTpShoppingCar
     * @return
     * @throws Exception
     */
    public Map<String, Object> checkShoppingCar(TmTpShoppingCar tmTpShoppingCar, BigDecimal userId,
                                                String openId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        Integer userPoints = null;
        // 获取潜客类型
        String sourceTypeStr = tmTpProductDetailMapper.querySourceType(openId);
        Integer sourceTypeInt = Integer.valueOf(sourceTypeStr);
        logger.info("获取潜客类型：" + sourceTypeInt);
        if (sourceTypeInt == 10011002) {
            // 调用第三方接口
            logger.info("调用第三方接口：");
            String url = getTotalURL;
            logger.info("url---" + url);
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("ifcode", "IC021");
            JSONArray jsonAray = new JSONArray();
            JSONObject jsonBody2 = new JSONObject();
            jsonBody2.put("openID", openId);
            logger.info("调用第三方接口openId：" + openId);
            jsonAray.add(jsonBody2);
            jsonBody.put("ifdata", jsonAray);
            String jsonBody3 = jsonBody.toString();
            logger.info("jsonBody---" + jsonBody3);
            String resultStr = FrameHttpUtil.postJson(url, jsonBody3);
            JSONObject data = JSONObject.fromObject(resultStr);
            Integer dataResult = data.getInt("result");
            if (dataResult == 200) {
                JSONArray resultList = data.getJSONArray("resultList");
                if (resultList != null && resultList.size() != 0) {
                    // 获得第三方积分返回points分
                    userPoints = (int) resultList.getJSONObject(0).getLong("points");
                    logger.info("获得第三方积分：" + userPoints);
                }
            } else if (dataResult == 500) {
                JSONArray resultList = data.getJSONArray("message");
                if (resultList != null && resultList.size() != 0) {
                    String message = resultList.getJSONObject(0).getString("openID");
                    logger.info("请求返回错误原因：" + message);
                }
            }
        } else {
            // 调用本地方法查出个人积分
            userPoints = tmTpProductDetailMapper.queryUserPoints(openId);
        }
        logger.info("个人积分——————————————————" + userPoints);
        Long num = tmTpShoppingCar.getNum();
        logger.info("传入商品数------" + num);

        TmTpShoppingCar po = new TmTpShoppingCar();
        po.setUserId(userId);
        BigDecimal productPoints = new BigDecimal(0);
        BigDecimal JDproductPoints = new BigDecimal(0);
        List<TmTpShoppingCar> list = tmTpShoppingCarMapper.selectShoppingCar(po.getUserId(), RATIO);
        for (TmTpShoppingCar shoppingCar : list) {
            if (tmTpShoppingCar.getSkuId() != shoppingCar.getSkuId()) {
                productPoints = productPoints.add(new BigDecimal(shoppingCar.getPrice()).multiply(new BigDecimal(shoppingCar.getNum())));
                logger.info("JDPRICE为》》》》》》" + productPoints);
                JDproductPoints = JDproductPoints.add(new BigDecimal(shoppingCar.getJdPrice()).multiply(new BigDecimal(shoppingCar.getNum())));
                logger.info("PRICE为》》》》》》" + JDproductPoints);
            }
        }
        if (num == null) {
            num = 1L;
        }
        if (tmTpShoppingCar.getPrice() == null) {
            tmTpShoppingCar.setPrice("0");
        }
        if (tmTpShoppingCar.getJdPrice() == null) {
            tmTpShoppingCar.setJdPrice("0");
        }
        JDproductPoints = JDproductPoints.add(new BigDecimal(tmTpShoppingCar.getJdPrice()).multiply(new BigDecimal(num)));
        productPoints = productPoints.add(new BigDecimal(tmTpShoppingCar.getPrice()).multiply(new BigDecimal(num)));
        Double JDpoints = Math.ceil(JDproductPoints.doubleValue());
        Double points = Math.ceil(productPoints.doubleValue());
        logger.info("该订单商品总价为——————" + points);
        if (JDpoints <= 99) {
            // 需运费，加6积分
            points = points + 6;
            logger.info("商品总价+运费=" + points);
        } else {
            // 无需运费
            logger.info("无需运费");
        }
        if (userPoints != null && userPoints >= points) {
            flag = true;
        }
        result.put("flag", flag);
        result.put("points", points);
        logger.info("返回结果>>>>>>>>>>>>>>>>>>>>" + result);
        return result;
    }

    /**
     * 查询购物车信息
     * 
     * @author QianKun
     * @date 2017年4月17日
     * @param userId
     * @return
     * @throws Exception
     */
    public Map<String, Object> getShoppingCarDetail(String openId) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<TmTpShoppingCar> shoppingCarList = new ArrayList<TmTpShoppingCar>();
        Long sumNum = 0L;
        Long sumPrice = 0L;
        double yunPrice = 0L;
        Long totalPrice = 0L;
        Long feightPrice = 0L;
        // 根据OPENID拿到车主ID
//        List<CarOwnerDto> userDto = customerServiceInterface.getUserInfo(openId);
        String userid = tmTpOrderInfoMapper.queryUserIdByOpenId(openId);
        if (CheckUtil.NullOrEmpty(userid)) {
            // 非车主
            logger.info("不是车主！");
            resultMap.put("List", shoppingCarList);
            resultMap.put("sumNum", sumNum);
            resultMap.put("sumPrice", sumPrice);
        } else {
            // 将车主ID存入实体
            BigDecimal userId = new BigDecimal(userid);
            logger.info("车主ID——" + userId);
            try {
                // 查询购物车信息列表
                shoppingCarList = tmTpShoppingCarMapper.selectShoppingCar(userId, RATIO);
                for (TmTpShoppingCar scDto : shoppingCarList) {
                    // 计算总数
                    sumNum = sumNum + scDto.getNum();
                    // 计算总价
                    sumPrice = sumPrice
                               + ((Integer.valueOf(scDto.getPrice()) * Integer.valueOf(scDto.getNum().toString())));
                    yunPrice = yunPrice
                               + ((Double.valueOf(scDto.getJdPrice()) * Integer.valueOf(scDto.getNum().toString())));
                    // 获取商品规格
                    String skuId = scDto.getSkuId();
                    Map<String, Object> productGroup = tmTpShoppingCarMapper.selectGroup(skuId);
                    if (productGroup != null) {
                        scDto.setProductGroup(productGroup.get("productGroup").toString());
                    }
                    // logger.info("scDto.getWxState()"+scDto.getWxState());
                    logger.info("scDto.getState().........." + scDto);
                    // 判断上下架状态
                    if (!CheckUtil.NullOrEmpty(scDto.getWxState()) && !CheckUtil.NullOrEmpty(scDto.getState()) && !CheckUtil.NullOrEmpty(scDto.getSaleState())) {
                        if ("30031001".equals(scDto.getWxState()) && "30021001".equals(scDto.getState())
                            && "30091001".equals(scDto.getSaleState())) {
                            // 上架
                            scDto.setFlag(1);
                            scDto.setMsg("已上架");
                        } else {
                            // 下架
                            scDto.setFlag(0);
                            scDto.setMsg("已下架");
                        }
                    } else {
                        scDto.setFlag(0);
                        scDto.setMsg("已下架");
                    }
                }

                // 计算商品总价格加上运费
                if (yunPrice >= 99) {
                    totalPrice = sumPrice;
                } else if (yunPrice <= 0) {
                    totalPrice = 0L;
                    feightPrice = 0L;
                } else {
                    totalPrice = sumPrice + 6;
                    feightPrice = 6L;
                }

                resultMap.put("List", shoppingCarList);
                resultMap.put("sumNum", sumNum);
                resultMap.put("sumPrice", sumPrice);
                resultMap.put("totalPrice", totalPrice);
                resultMap.put("feightPrice", feightPrice);
            } catch (Exception e) {
                logger.info("Exception:", e);
                throw new ServiceBizException(e.getMessage(), e);
            }
        }
        return resultMap;
    }

    /**
     * 查询购物车总价和总数
     * 
     * @author lyq
     * @date 2017年5月5日
     * @param userId
     * @return
     * @throws Exception
     */
    public Map<String, Object> getCarSumPriceNum(String openId) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> shoppingCarList = new ArrayList<Map<String, Object>>();
        Long sumNum = 0L;
        BigDecimal sumPrice = new BigDecimal(0);
        // 根据OPENID拿到车主ID
//        List<CarOwnerDto> userDto = customerServiceInterface.getUserInfo(openId);
        String userid = tmTpOrderInfoMapper.queryUserIdByOpenId(openId);
        if (CheckUtil.NullOrEmpty(userid)) {
            // 非车主
            logger.info("不是车主！");
            resultMap.put("sumNum", sumNum);
            resultMap.put("sumPrice", sumPrice);
        } else {
            // 将车主ID存入实体
            BigDecimal userId = new BigDecimal(userid);
            logger.info("车主ID——" + userId);
            try {
                // 查询购物车信息列表
                shoppingCarList = tmTpShoppingCarMapper.selectSumPriceNum(userId, RATIO);
                resultMap = shoppingCarList.get(0);
            } catch (Exception e) {
                logger.info("Exception:", e);
                throw new ServiceBizException(e.getMessage(), e);
            }
        }
        return resultMap;
    }

    /**
     * 删除购物车信息
     * 
     * @author QianKun
     * @date 2017年4月17日
     * @param userId
     * @param skuId
     * @return
     * @throws Exception
     */
    public Map<String, Object> deleteShoppingCar(TmTpShoppingCar tmTpShoppingCar, String openId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        // 创建日期对象
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(d);
        // 根据OPENID拿到车主ID
//        List<CarOwnerDto> userDto = customerServiceInterface.getUserInfo(openId);
        String userid = tmTpOrderInfoMapper.queryUserIdByOpenId(openId);
        if (CheckUtil.NullOrEmpty(userid)) {
            // 非车主
            logger.info("不是车主！");
        } else {
            // 将车主ID存入实体
            BigDecimal userId = new BigDecimal(userid);
            String skuId = tmTpShoppingCar.getSkuId();
            logger.info("车主ID——" + userId);
            logger.info("商品ID——" + skuId);
            try {
                // 删除购物车信息
                tmTpShoppingCarMapper.deleteShoppingCar(userId, skuId);

                result.put("code", "200");
                result.put("data", "删除成功");
                result.put("message", "OK");
                result.put("time", date);
            } catch (Exception e) {
                logger.info("Exception:", e);
                result.put("code", "500");
                result.put("data", "");
                result.put("message", e.getMessage());
                result.put("time", date);
            }
        }
        return result;
    }

    /**
     * 获取商品列表
     * 
     * @author QianKun
     * @date 2017年4月14日
     * @param pageSize
     * @return
     * @throws Exception
     */
    public PageInfo<TmTpProductDetail> getProductDetail(Map<String, Object> queryMap,
                                                        List<String> list) throws Exception {
        try {
            // useType=0 根据openId获取当前登录积分
            if (!CheckUtil.NullOrEmpty(queryMap.get("useType"))) {
                Integer userPoints = null;
                Integer type = Integer.valueOf(queryMap.get("useType").toString());
                if (type == 0 && !CheckUtil.NullOrEmpty(queryMap.get("openId"))) {
                    String openId = queryMap.get("openId").toString();
                    userPoints = tmTpProductDetailMapper.queryUserPoints(openId);
                    logger.info(" 积分..............................." + userPoints);
                    if (userPoints == null) {
                        userPoints = 0;
                    }
                }
                queryMap.put("userPoints", userPoints);
            }
            // 查询商品列表
            Page<TmTpProductDetail> ss = PageHelper.startPage(Integer.parseInt(queryMap.get("pageNum").toString()),
                                                              Integer.parseInt(queryMap.get("pageSize").toString()));
            logger.info("ss为————" + ss);

            if (!CheckUtil.NullOrEmpty(queryMap.get("category"))) {
                String category = queryMap.get("category").toString();
                int i = category.indexOf(",");
                if (i < 0) {
                    queryMap.put("category1", category);
                    queryMap.put("category2", null);
                    queryMap.put("category3", null);
                } else {
                    String[] ca = category.split(",");
                    if (ca.length == 2) {
                        queryMap.put("category1", ca[0]);
                        queryMap.put("category2", ca[1]);
                        queryMap.put("category3", null);
                    } else {
                        queryMap.put("category1", ca[0]);
                        queryMap.put("category2", ca[1]);
                        queryMap.put("category3", ca[2]);
                    }
                }

            } else {
                queryMap.put("category1", null);
                queryMap.put("category2", null);
                queryMap.put("category3", null);
            }
            queryMap.put("RATIO", RATIO);
            List<TmTpProductDetail> pd = tmTpProductDetailMapper.selectAllProduct(queryMap, list);
            logger.info("pd为————" + pd.toString());
            PageInfo<TmTpProductDetail> page = new PageInfo<TmTpProductDetail>(pd);
            return page;

        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 商品列表
     * 
     * @param queryMap
     * @return
     * @throws Exception
     */
    public List<TmTpProductDetail> getProductList(Map<String, Object> queryMap) throws Exception {
        try {
            List<String> list = null;
            if (!CheckUtil.NullOrEmpty(queryMap.get("category"))) {
                String category = queryMap.get("category").toString();
                int i = category.indexOf(",");
                if (i < 0) {
                    queryMap.put("category1", category);
                    queryMap.put("category2", null);
                    queryMap.put("category3", null);
                } else {
                    String[] ca = category.split(",");
                    if (ca.length == 2) {
                        queryMap.put("category1", ca[0]);
                        queryMap.put("category2", ca[1]);
                        queryMap.put("category3", null);
                    } else {
                        queryMap.put("category1", ca[0]);
                        queryMap.put("category2", ca[1]);
                        queryMap.put("category3", ca[2]);
                    }
                }

            } else {
                queryMap.put("category1", null);
                queryMap.put("category2", null);
                queryMap.put("category3", null);
            }
            queryMap.put("RATIO", RATIO);
            // 查询商品列表
            List<TmTpProductDetail> pd = tmTpProductDetailMapper.selectAllProduct(queryMap, list);
            // logger.info("pd为————" + pd.toString());
            return pd;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    /**
     * 获取商品
     * 
     * @author QianKun
     * @date 2017年4月14日
     * @param pageSize
     * @return
     * @throws Exception
     */
    public Map<String, Object> getProductDetailInfo(String sku) throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        List<String> list = null;
        if (sku == "" || sku == null) {
            data.put("flag", 0);
            data.put("msg", "sku为空！");
        } else {
            // 查询商品详情通用子表
            List<TmTpProductDetailGeneral> pdg = null;
            // 查询商品详情BOOK子表
            List<TmTpProductDetailBook> pdb = null;
            // 查询商品详情VEDIO子表
            List<TmTpProductDetailVido> pdv = null;
            // 查询商品详情
            Map<String, Object> queryMap = new HashMap<String, Object>();

            queryMap.put("goodsNo", sku);

            // 判断是否存在该商品规格
            Integer ifExistGroup = tmTpProductDetailMapper.queryGroup(sku);
            if (ifExistGroup > 0) {
                ifExistGroup = 1;
            } else {
                ifExistGroup = 0;
            }
            data.put("ifExistGroup", ifExistGroup);

            queryMap.put("RATIO", RATIO);
            List<TmTpProductDetail> pd = tmTpProductDetailMapper.selectAllProduct(queryMap, list);

            if (pd != null && pd.size() > 0) {
                data.put("productDetail", pd.get(0));
                logger.info("pd为————" + pd.toString());
                String skuType = pd.get(0).getSkutype();
                if (skuType == null || skuType.equals("")) {
                    TmTpProductDetailGeneral param = new TmTpProductDetailGeneral();
                    param.setSku(sku);
                    pdg = productDetailGeneralMapper.select(param);
                    if (pdg != null && pdg.size() > 0) {
                        dealContent(pdg);
                        data.put("productDetailGeneral", pdg.get(0));
                        data.put("productDetailBook", null);
                        data.put("productDetailVedio", null);
                    } else {
                        throw new Exception("该商品详情");
                    }
                } else if (skuType.equals("book")) {
                    TmTpProductDetailBook param = new TmTpProductDetailBook();
                    param.setSku(sku);
                    pdb = productDetailBookMapper.select(param);
                    if (pdb != null && pdb.size() > 0) {
                        dealContentBook(pdb);
                        data.put("productDetailBook", pdb.get(0));
                        data.put("productDetailGeneral", null);
                        data.put("productDetailVedio", null);
                    } else {
                        throw new Exception("该商品详情");
                    }
                } else if (skuType.equals("vedio")) {
                    TmTpProductDetailVido param = new TmTpProductDetailVido();
                    param.setSku(sku);
                    pdv = productDetailVidoMapper.select(param);
                    if (pdv != null && pdv.size() > 0) {
                        dealContentVido(pdv);
                        data.put("productDetailGeneral", null);
                        data.put("productDetailBook", null);
                        data.put("productDetailVedio", pdv.get(0));
                    } else {
                        throw new Exception("该商品详情");
                    }
                }
            } else {
                throw new Exception("该商品不存在");
            }
            data.put("flag", 1);
            data.put("msg", "sku不为空！");
        }
        return data;
    }

    /**
     * 处理根据路径获取内容
     * 
     * @author QianKun
     * @date 2017年3月10日
     * @param naiId
     * @return
     */
    public void dealContent(List<TmTpProductDetailGeneral> list) {
        if (list != null && list.size() > 0) {
            for (TmTpProductDetailGeneral po : list) {
                if (!CheckUtil.NullOrEmpty(po.getParam()) && po.getParam() != "null" && !po.getParam().equals("null")) {
                    String c = CommonUtils.getUrlToContent(po.getParam());
                    po.setParam(c);
                }
                if (!CheckUtil.NullOrEmpty(po.getIntroductionExtend()) && po.getIntroductionExtend() != "null"
                    && !po.getIntroductionExtend().equals("null")) {
                    String i = CommonUtils.getUrlToContent(po.getIntroductionExtend());
                    po.setIntroduction(i);
                }
                if (!CheckUtil.NullOrEmpty(po.getAppintroduceExtend()) && po.getAppintroduceExtend() != "null"
                    && !po.getAppintroduceExtend().equals("null")) {
                    String a = CommonUtils.getUrlToContent(po.getAppintroduceExtend());
                    po.setAppintroduce(a);
                }
            }
        }

    }

    /**
     * 处理根据路径获取内容
     * 
     * @author QianKun
     * @date 2017年3月10日
     * @return
     */
    public void dealContentVido(List<TmTpProductDetailVido> list) {
        if (list != null && list.size() > 0) {
            for (TmTpProductDetailVido po : list) {
                if (!CheckUtil.NullOrEmpty(po.getContentdesc()) && !po.getContentdesc().equals("null")) {
                    String contentdesc = CommonUtils.getUrlToContent(po.getContentdesc());
                    po.setContentdesc(contentdesc);
                }
                if (!CheckUtil.NullOrEmpty(po.getEditerdesc()) && !po.getEditerdesc().equals("null")) {
                    String editerdesc = CommonUtils.getUrlToContent(po.getEditerdesc());
                    po.setEditerdesc(editerdesc);
                }
                if (!CheckUtil.NullOrEmpty(po.getCatalogue()) && !po.getCatalogue().equals("null")) {
                    String catalogue = CommonUtils.getUrlToContent(po.getCatalogue());
                    po.setCatalogue(catalogue);
                }
                if (!CheckUtil.NullOrEmpty(po.getComments()) && !po.getComments().equals("null")) {
                    String comments = CommonUtils.getUrlToContent(po.getComments());
                    po.setComments(comments);
                }
            }
        }

    }

    /**
     * 处理根据路径获取内容
     * 
     * @author QianKun
     * @date 2017年3月10日
     * @param naiId
     * @return
     */
    public void dealContentBook(List<TmTpProductDetailBook> list) {
        if (list != null && list.size() > 0) {
            for (TmTpProductDetailBook po : list) {
                if (!CheckUtil.NullOrEmpty(po.getContentdesc()) && !po.getContentdesc().equals("null")) {
                    String contentdesc = CommonUtils.getUrlToContent(po.getContentdesc());
                    po.setContentdesc(contentdesc);
                }
                if (!CheckUtil.NullOrEmpty(po.getEditerdesc()) && !po.getEditerdesc().equals("null")) {
                    String editerdesc = CommonUtils.getUrlToContent(po.getEditerdesc());
                    po.setEditerdesc(editerdesc);
                }
                if (!CheckUtil.NullOrEmpty(po.getAuthordesc()) && !po.getAuthordesc().equals("null")) {
                    String authordesc = CommonUtils.getUrlToContent(po.getAuthordesc());
                    po.setAuthordesc(authordesc);
                }
                if (!CheckUtil.NullOrEmpty(po.getComments()) && !po.getComments().equals("null")) {
                    String comments = CommonUtils.getUrlToContent(po.getComments());
                    po.setComments(comments);
                }
            }
        }

    }

    /**
     * @param map userId,status,sku
     * @return
     */
    public int updateGoodsStatus(Map<String, Object> map) throws Exception {

        if (map.get("sku") == null || map.get("sku").toString().equals("")) {
            throw new Exception("sku 不能为空");
        }

        // if (map.get("userId") == null || map.get("userId").toString().equals("")) {
        // throw new Exception("userId 不能为空");
        // }

        if (map.get("status") == null || map.get("status").toString().equals("")) {
            throw new Exception("status 不能为空");
        }

        // 更新状态
        Example goodsExample = new Example(TmTpProductDetail.class);
        goodsExample.createCriteria().andCondition("sku = ", map.get("sku").toString());
        TmTpProductDetail goodsValue = new TmTpProductDetail();
        goodsValue.setWxstate(Integer.parseInt(map.get("status").toString()));

        // 上架的时候才修改上架时间
        if (Integer.parseInt(map.get("status").toString()) == ShoppingConstant.WX_STATUS_UP) {
            goodsValue.setUpDate(new Date());
        } else {
            goodsValue.setUpDate(null);
        }
        goodsValue.setUpdateDate(new Date());
        // goodsValue.setUpdateBy(Integer.parseInt(map.get("userId").toString()));

        int i = tmTpProductDetailMapper.updateByExampleSelective(goodsValue, goodsExample);

        return i;
    }

    /**
     * 更新是否是热点
     * 
     * @param map userId,status,sku
     * @return
     */
    public int updateGoodsIsHot(Map<String, Object> map) throws Exception {

        if (map.get("sku") == null || map.get("sku").toString().equals("")) {
            throw new Exception("sku 不能为空");
        }

        // if (map.get("userId") == null || map.get("userId").toString().equals("")) {
        // throw new Exception("userId 不能为空");
        // }

        if (map.get("status") == null || map.get("status").toString().equals("")) {
            throw new Exception("status 不能为空");
        }

        // 更新状态
        Example goodsExample = new Example(TmTpProductDetail.class);
        goodsExample.createCriteria().andCondition("sku = ", map.get("sku").toString());
        TmTpProductDetail goodsValue = new TmTpProductDetail();
        goodsValue.setIshot(Integer.parseInt(map.get("status").toString()));
        goodsValue.setUpdateDate(new Date());
        // goodsValue.setUpdateBy(Integer.parseInt(map.get("userId").toString()));

        int i = tmTpProductDetailMapper.updateByExampleSelective(goodsValue, goodsExample);

        return i;
    }

    /**
     * 取消未确认订单
     * 
     * @param jdOrderId
     * @return
     */
    public List<Map<String, Object>> cancelJDOrder(String thirdOrder) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        // 创建Example
        Example example = new Example(TmTpOrderInfo.class);
        example.createCriteria().andCondition("THIRD_ORDER=", thirdOrder);
        // 根据第三方单号拿到JD单号
        List<TmTpOrderInfo> tpOrder = tmTpOrderInfoMapper.selectByExample(example);
        String jdOrderId = tpOrder.get(0).getJdOrderId();
        // 调用京东取消订单接口
        Response<List<Map<String, Object>>> result = shoppingServiceInterface.cancelOrder(jdOrderId);
        list.add((Map<String, Object>) result.getData());
        return list;
    }

    /**
     * 商品区域购买限制查询
     * 
     * @param jdOrderId
     * @return
     */
    public List<Map<String, Object>> checkAreaLimit(Map<String, Object> param) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        logger.error("调京东商品区域购买限制查询....start");
        Response<List<Map<String, Object>>> result = shoppingServiceInterface.checkAreaLimit(param);
        Integer code = result.getResultCode();
        if (code == ResultMsgConstants.RESULT_CODE_SUCCESS) {
            list = result.getData();
        }
        logger.error("调京东商品区域购买限制查询....end");
        return list;
    }

    /**
     * 批量获取库存接口（建议订单详情页、下单使用）
     * 
     * @param jdOrderId
     * @return
     */
    public List<Map<String, Object>> getNewStockById(Map<String, Object> param) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        logger.error("调京东批量获取库存接口查询....getNewStockById.start");
        Response<List<Map<String, Object>>> result = shoppingServiceInterface.getNewStockById(param);
        Integer code = result.getResultCode();
        if (code == ResultMsgConstants.RESULT_CODE_SUCCESS) {
            list = result.getData();
        }
        logger.error("调京东批量获取库存接口查询....getNewStockById.end");
        return list;
    }

    /**
     * 批量获取库存接口(建议商品列表页使用)
     * 
     * @param jdOrderId
     * @return
     */
    public List<Map<String, Object>> getStockById(Map<String, Object> param) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        logger.error("调京东批量获取库存接口查询....getStockById.start");
        Response<List<Map<String, Object>>> result = shoppingServiceInterface.getStockById(param);
        Integer code = result.getResultCode();
        if (code == ResultMsgConstants.RESULT_CODE_SUCCESS) {
            list = result.getData();
        }
        logger.error("调京东批量获取库存接口查询....getStockById.end");
        return list;
    }

    /**
     * 调用JD下单接口
     * 
     * @author Administrator TODO description
     * @date 2017年4月27日
     * @return
     */
    public Map<String, String> submitJDOrder(Map<String, Object> queryMap) {
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            // 调用京东下单接口
            logger.info("调用京东下单接口——Start");
            Map<String, Object> submitResult = new HashMap<String, Object>();
            String thirdOrder = queryMap.get("thirdOrder").toString();
            String userId = queryMap.get("userId").toString();
            // Map<String, Object> queryMap = new HashMap<String, Object>();
            // queryMap.put("thirdOrder", thirdOrder);
            // queryMap.put("userId", userId);
            // queryMap.put("event", event);
            submitResult = shoppingServiceInterface.submitOrder(queryMap);
            String resultCode = submitResult.get("errorCode").toString();
            logger.info("调用下单接口返回CODE——" + resultCode);
            // 将京东返回CODE存入订单表中
            TmTpOrderInfo orderInfos = new TmTpOrderInfo();
            orderInfos.setJdCode(ShoppingConstant.JD_CODE + resultCode);
            logger.info("创建Example");
            Example ex = new Example(TmTpOrderInfo.class);
            ex.createCriteria().andCondition("THIRD_ORDER=", thirdOrder);
            int a = tmTpOrderInfoMapper.updateByExampleSelective(orderInfos, ex);
            logger.info("更新结果：" + a);
            String resultMsg = submitResult.get("resultMsg").toString();
            logger.info("调用下单接口返回信息——" + resultMsg);
            TmTpOrderInfo orderInfo = new TmTpOrderInfo();
            if (resultCode.equals("0001")) {
                // 调用京东下单接口成功
                logger.info("下单成功！");
                orderInfo.setOrderStatus(ShoppingConstant.ORDER_STATUS_SUCCESS);
                logger.info("状态为——" + orderInfo.getOrderStatus());
                // 创建Example
                logger.info("创建Example");
                Example example = new Example(TmTpOrderInfo.class);
                example.createCriteria().andCondition("THIRD_ORDER=", thirdOrder);
                int i = tmTpOrderInfoMapper.updateByExampleSelective(orderInfo, example);
                logger.info("更新结果：" + i);
                resultMap.put("resultCode", ShoppingConstant.ORDER_STATUS_SUCCESS);
                resultMap.put("resultMsg", "京东下单成功");
            } else {
                // 调用京东下单接口失败
                logger.info("下单失败！");
                orderInfo.setOrderStatus(ShoppingConstant.ORDER_STATUS_FIALED);
                logger.info("状态为——" + orderInfo.getOrderStatus());
                // 创建Example
                logger.info("创建Example");
                Example example = new Example(TmTpOrderInfo.class);
                example.createCriteria().andCondition("THIRD_ORDER=", thirdOrder);
                int i = tmTpOrderInfoMapper.updateByExampleSelective(orderInfo, example);
                logger.info("更新结果：" + i);
                resultMap.put("resultCode", ShoppingConstant.ORDER_STATUS_FIALED);
                resultMap.put("resultMsg", "京东下单失败");
            }
        } catch (Exception e) {
            logger.info("Exception:", e);
            resultMap.put("resultCode", ShoppingConstant.ORDER_STATUS_FIALED);
            resultMap.put("resultMsg", "京东下单异常");
        }
        return resultMap;
    }

    /**
     * 统一余额查询
     * 
     * @param param
     * @return
     */
    public List<Map<String, Object>> getBalance(Map<String, Integer> param) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        logger.info("调京东统一余额接口查询....getBalance.start");
        Response<List<Map<String, Object>>> result = shoppingServiceInterface.getBalance(param);
        logger.info("调京东统一余额接口查询....getBalance.end" + result);
        Integer code = result.getResultCode();
        if (code == ResultMsgConstants.RESULT_CODE_SUCCESS) {
            list = result.getData();
            logger.info("调京东统一余额接口查询....getBalance.end" + list);
        }
        logger.info("调京东统一余额接口查询....getBalance.end");
        return list;
    }

    /**
     * 用户金彩余额查询
     * 
     * @param param
     * @return
     */
    public Map<String, Object> selectJincaiCredit() {
        Map<String, Object> map = new HashMap<String, Object>();
        logger.info("用户金彩余额查询....selectJincaiCredit.start");
        Response<Map<String, Object>> result = shoppingServiceInterface.selectJincaiCredit();
        logger.info("用户金彩余额查询....selectJincaiCredit.end" + result);
        Integer code = result.getResultCode();
        if (code == ResultMsgConstants.RESULT_CODE_SUCCESS) {
            map = result.getData();
            logger.info("用户金彩余额查询....selectJincaiCredit.end" + map);
        }
        logger.info("用户金彩余额查询....selectJincaiCredit.end");
        return map;
    }

    /**
     * 余额明细查询
     * 
     * @param orderId
     * @return
     */
    public PageInfo<TmTpBalanceDetail> getBalanceDetail(Map<String, Object> paramMap){

    	// 查询余额明细列表
        Page<TmTpBalanceDetail> ss = PageHelper.startPage(Integer.parseInt(paramMap.get("pageNum").toString()),
                                                          Integer.parseInt(paramMap.get("pageSize").toString()));
        logger.info("余额明细查询开始:");
        List<TmTpBalanceDetail> list = tmTpBalanceDetailMapper.getBalanceDetail(paramMap);
        logger.info("余额明细查询结束:");
        PageInfo<TmTpBalanceDetail> page = new PageInfo<TmTpBalanceDetail>(list);
        logger.info("分页余额明细查询结束:");
        return page;
    }

    /**
     * 导出余额明细信息
     * 
     * @param paramMap
     * @return
     * @throws Exception
     */
    public List<TmTpBalanceDetail> balanceDetailExport(Map<String, Object> paramMap) {

    	logger.info("余额明细查询开始:");
        List<TmTpBalanceDetail> balanceDetailList = tmTpBalanceDetailMapper.getBalanceDetail(paramMap);
        logger.info("余额明细查询结束:");
        return balanceDetailList;
    }

    public String shoppingSendMq(String openId, Long deductPoints) throws Exception {
        String s = "";
        try {
            logger.info("MaintainSend——Start");
            SendMessage<List<EventShoppingSendWeixinDto>> l = new SendMessage<List<EventShoppingSendWeixinDto>>();
            List<EventShoppingSendWeixinDto> list = new ArrayList<EventShoppingSendWeixinDto>();
            EventShoppingSendWeixinDto dto = new EventShoppingSendWeixinDto();
            dto.setOpenID(openId);
            logger.info("参数OPEN_ID>>>>>>>>>>>>" + dto.getOpenID());
            dto.setPoints(deductPoints);
            logger.info("参数deductPoints>>>>>>>>>>>>" + dto.getPoints());
            list.add(dto);
            logger.info("dto添加入list中");
            l.setIfcode("IC022");
            l.setIfdata(list);
            logger.info("list拼到IfData中");
            String data = JSON.toJSONString(l).toString();
            logger.info("推送到MQ的数据为>>>>>" + data);
            s = eventService.sendMessage2MQ(MQChannelType.appShoppingPoints, data);
            logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
            logger.info("SendEnd");
            return s;
        } catch (Exception e) {
            logger.info("调用MQ异常：" + e.getMessage());
            throw e;
        }
    }

    public Map<String, Object> selectAddName(String addr) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        String first = "";
        String second = "";
        String third = "";
        try {
            String a[] = addr.split("_");
            first = tmTpReceiveAddMapper.selectAddName(a[0]);
            second = tmTpReceiveAddMapper.selectAddName(a[1]);
            third = tmTpReceiveAddMapper.selectAddName(a[2]);
            result.put("addr", addr);
            result.put("first", first);
            result.put("second", second);
            result.put("third", third);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return result;
    }

    public Map<String, Object> selectRecAdd(String openId) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        String addr = "";
        String first = "";
        String second = "";
        String third = "";
        try {
            List<ReceiveAdd> list = tmTpReceiveAddMapper.queryReceiveAdd(openId);
            if (list.size() == 0) {
                logger.info("该用户没有维护收货地址");
                addr = "1_0_0";
                first = "北京";
            } else {
                addr = list.get(0).getFirstAddCode() + "_" + list.get(0).getSecondAddCode() + "_"
                       + list.get(0).getThirdAddCode();
                first = list.get(0).getFirstAdd();
                second = list.get(0).getSecondAdd();
                third = list.get(0).getThirdAdd();
            }
            result.put("addr", addr);
            result.put("first", first);
            result.put("second", second);
            result.put("third", third);
        } catch (Exception e) {
            logger.info("查询发生异常：" + e.getMessage());
        }
        return result;
    }

    public boolean selectStockById(String addr, HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        boolean flag = false;
        String sku = "";
        List<String> list1 = new ArrayList<String>();
        String productNo = "(";
        List<String> list = new ArrayList<String>();
        try {
            // 查询出需要的商品
            List<TmTpProductDetail> productList = tmTpProductDetailMapper.selectSku();
            logger.info("一共有" + productList.size() + "件商品");
            if (productList.size() == 0) {
                logger.info("没有上架商品");
            } else if (productList.size() == 1) {
                logger.info("只有一个商品");
                sku = productList.get(0).getSku();
            } else {
                for (int i = 0; i < productList.size(); i++) {
                    // if((i+1)%100==0||i==productList.size()-1){
                    if ((i + 1) % 100 == 0) {
                        sku = sku + productList.get(i).getSku();
                    } else {
                        if (i != productList.size() - 1) {
                            sku = sku + productList.get(i).getSku() + ",";
                            continue;
                        } else {
                            sku = sku + productList.get(i).getSku();
                        }
                    }
                    list1 = getStock(sku, addr);
                    if (list1 == null) {
                        logger.info("不存在无货的商品");
                    } else {
                        for (int s = 0; s < list1.size(); s++) {
                            list.add(list1.get(s));
                        }
                    }
                    sku = "";
                    // }
                }
                for (int m = 0; m < list.size(); m++) {
                    if (m == list.size() - 1) {
                        productNo = productNo + list.get(m) + ")";
                    } else {
                        productNo = productNo + list.get(m) + ",";
                    }
                }
                if (productNo.equals("(")) {
                    productNo = "";
                }
                // list转成json
                String json = JSONArray.fromObject(list).toString();
                logger.info("以下商品无货:" + json);
                // 将无货的sku写入cookie
                Cookie cookies = new Cookie("SKU", CookieSecurityUtil.encrypt(json));
                cookies.setMaxAge(1 * 60 * 60);// 1小时有效期
                cookies.setPath(request.getContextPath());
                // cookies.setDomain("i-club.gmmc.com.cn");
                response.addCookie(cookies);
                flag = true;
            }

        } catch (Exception e) {
            logger.info("查询异常:" + e.getMessage(), e);
        }
        return flag;
    }

    public List<String> getStock(String sku, String addr) throws Exception {
        List<String> list = new ArrayList<String>();
//
//        Map<String, Object> params = new HashMap<String, Object>();
//        Map<String, Object> newStockData = new HashMap<String, Object>();
//        // 返回值
//        String area = "";
//        String desc = "";
//        String skus = "";
//        String state = "";
//        try {
//            params.put("sku", sku);
//            params.put("area", addr);
//            // 调用接口
//            // logger.info("接口入参params：" + params);
//            Response newStockResult = shoppingServiceInterface.getStockById(params);
//            // logger.info("返回结果——" + newStockResult);
//            List<Map<String, Object>> newStockList = (List<Map<String, Object>>) newStockResult.getData();
//            logger.info("返回Data——" + newStockList);
//            if (newStockList == null) {
//                logger.info("接口调用失败——" + newStockResult.getErrMsg());
//            } else {
//                for (int d = 0; d < newStockList.size(); d++) {
//                    newStockData = newStockList.get(d);
//                    // logger.info("结果："+newStockData);
//                    area = newStockData.get("area").toString();
//                    // logger.info("地址为："+area);
//                    desc = newStockData.get("desc").toString();
//                    // logger.info("描述为："+desc);
//                    skus = newStockData.get("sku").toString();
//                    logger.info("SKU为：" + skus);
//                    state = newStockData.get("state").toString();
//                    logger.info("状态为：" + state);
//                    if (state.equals("34")) {
//                        logger.info(skus + "该商品无货");
//                        list.add(skus);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            logger.info(e.getMessage(), e);
//        }
        return list;
    }

    @SuppressWarnings("unchecked")
	public List<Map<String, Object>> productCategorys() throws Exception {
        List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
        try {
            List<Map<String, Object>> categoryList = tmTpProductCategoryMapper.selectCategory1();

            List<Map<String, Object>> l1 = CATEGORY1(categoryList);
            for (Map<String, Object> map : l1) {
                List<Map<String, Object>> l11 = (List<Map<String, Object>>) map.get("records");
                List<Map<String, Object>> l2 = CATEGORY2(l11);
                List<Map<String, Object>> l3 = new ArrayList<Map<String, Object>>();
                for (Map<String, Object> map2 : l2) {
                    List<Map<String, Object>> l22 = (List<Map<String, Object>>) map2.get("records");
                    l3 = CATEGORY3(l22);
                    for (Map<String, Object> map3 : l3) {
                        List<Map<String, Object>> l33 = (List<Map<String, Object>>) map3.get("records");
                        String pid = l33.get(0).get("CATEGORY1").toString() + ","
                                     + l33.get(0).get("CATEGORY2").toString() + ","
                                     + l33.get(0).get("CATEGORY3").toString();
                        String Level_Name = l33.get(0).get("NAME1").toString() + ","
                                            + l33.get(0).get("NAME2").toString() + ","
                                            + l33.get(0).get("NAME3").toString();
                        map3.put("PID", pid);
                        map3.put("Level_Name", Level_Name);
                        map3.remove("records");
                    }
                    map2.put("child", l3);
                    map2.remove("records");
                }
                map.put("child", l2);
                map.remove("records");
            }

            return l1;
        } catch (Exception e) {
            logger.info("Exception:", e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
	public List<Map<String, Object>> CATEGORY1(List<Map<String, Object>> list) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (!CheckUtil.NullOrEmpty(list)) {
            // 汇总分组数据
            for (Map<String, Object> record : list) {
                String c1 = (String) record.get("CATEGORY1");
                String n1 = (String) record.get("NAME1");
                Map<String, Object> dataMap = null;
                dataMap = CATEGORY(result, c1, n1, "1");
                List<Map<String, Object>> records_ = (List<Map<String, Object>>) dataMap.get("records");
                records_.add(record);
                dataMap.put("id", c1);
                dataMap.put("name", n1);
            }
        }
        return result;
    }

    public List<Map<String, Object>> CATEGORY2(List<Map<String, Object>> list) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (!CheckUtil.NullOrEmpty(list)) {
            // 汇总分组数据
            for (Map<String, Object> record : list) {
                String c1 = (String) record.get("CATEGORY2");
                String n1 = (String) record.get("NAME2");
                Map<String, Object> dataMap = null;
                dataMap = CATEGORY(result, c1, n1, "2");
                List<Map<String, Object>> records_ = (List<Map<String, Object>>) dataMap.get("records");
                records_.add(record);
                dataMap.put("id", c1);
                dataMap.put("name", n1);
            }
        }
        return result;
    }

    public List<Map<String, Object>> CATEGORY3(List<Map<String, Object>> list) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (!CheckUtil.NullOrEmpty(list)) {
            // 汇总分组数据
            for (Map<String, Object> record : list) {
                String c1 = (String) record.get("CATEGORY3");
                String n1 = (String) record.get("NAME3");
                Map<String, Object> dataMap = null;
                dataMap = CATEGORY(result, c1, n1, "3");
                List<Map<String, Object>> records_ = (List<Map<String, Object>>) dataMap.get("records");
                records_.add(record);
                dataMap.put("id", c1);
                dataMap.put("name", n1);
            }
        }
        return result;
    }

    public Map<String, Object> CATEGORY(List<Map<String, Object>> dataMap, String c1, String n1, String level) {
        Map<String, Object> r = null;
        for (Map<String, Object> map : dataMap) {
            if (c1.equals(map.get("id"))) {
                r = map;
                break;
            }
        }
        if (r == null) {
            r = new HashMap<String, Object>();
            r.put("level", level);
            r.put("id", c1);
            r.put("name", n1);
            r.put("records", new ArrayList<Map<String, Object>>());
            dataMap.add(r);
        }
        return r;
    }

    public String selectopenIdByUserId(String userId) {
    	String openId = tmTpOrderInfoMapper.selectopenIdByUserId(userId);
    	return openId;
    }
}
